﻿using System.Data;
using Dapper;
using DataServer.ApplicationLib.Entities;
using DataServer.CommonLib.Models.DataConfig;
using Swimj.DataCore;

namespace DataServer.ApplicationLib.Repositories
{
    public class ConfigRuleRepository :
    IConfigRuleRepository
    {
        private readonly IDbConnection _dbConnection;

        public ConfigRuleRepository(IDbConnection dbConnection)
        {
            _dbConnection = dbConnection;
        }

        public async Task<IEnumerable<ConfigRuleEntity>> QueryRulesByConfigAsync(string configCode, ConfigRuleSearchRequestDto model)
        {
            var sql = @"select rule.Id,
       rule.configid,
       rule.RuleCode,
       rule.RuleName
from DS_CONFIGRULE rule
join DS_DATACONFIG config on rule.ConfigId = config.Id
where config.ConfigCode = @configCode
order by rule.Sort asc";

            return await _dbConnection.QueryAsync<ConfigRuleEntity>
                (sql, new
                {
                    configCode = configCode
                });
        }

        public async Task<Tuple<IEnumerable<ConfigRuleEntity>, int>> QueryRulesByPageConfigAsync(string configCode, ConfigRuleSearchRequestDto model)
        {

            var countSql = @"select count(1) from DS_CONFIGRULE rule
join DS_DATACONFIG config on rule.ConfigId = config.Id
where config.ConfigCode = @configCode";

            var totalCount = await _dbConnection.ExecuteScalarAsync<int>(countSql, new { configCode = configCode });

            var sql = @"select rule.Id,
       rule.configId,
       rule.RuleCode,
       rule.RuleName
from DS_CONFIGRULE rule
join DS_DATACONFIG config on rule.ConfigId = config.Id
where config.ConfigCode = @configCode
order by rule.Sort asc
LIMIT @offset,@rowsPerPage";

            var data = await _dbConnection.QueryAsync<ConfigRuleEntity>
                (sql, new
                {
                    configCode = configCode,
                    offset = (model.Page - 1) * model.Limit,
                    rowsPerPage = model.Limit
                });
            return new Tuple<IEnumerable<ConfigRuleEntity>, int>(data, totalCount);
        }
    }
}
